//
//  HomePageViewController.m
//  LOLProject
//
//  Created by lanou3g on 15/5/26.
//  Copyright (c) 2015年 lanou3g.com蓝欧科技. All rights reserved.
//

#import "HomePageViewController.h"

@interface HomePageViewController ()

@end

@implementation HomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
//    设置背景颜色
    self.view.backgroundColor=[UIColor whiteColor];
//    创建theLatestVideoTableView并作为默认视图
    [self createTheLatestVideoTableView];
//    创建videoGameTableView,暂不使用
    [self createVideoGameTableView];
//    创建hdBroadcastTableView,暂不使用
    [self createHdBroadcastTableView];
//    默认显示最新视频
    self.homePageSegmentedControl.selectedSegmentIndex=0;
    [self select:self.homePageSegmentedControl];
//    设置UISearchBar的代理
    self.homePageSearchBar.delegate=self;
//    设置UISearchBar的barStyle
    self.homePageSearchBar.barStyle=UIBarStyleBlackTranslucent;
//    设置UISearchBar的键盘风格
    self.homePageSearchBar.keyboardType=UIKeyboardTypeDefault;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


#pragma mark---设置UISegmentedControl添加的方法
- (void) select:(id)sender{
//    获取单例对象
    HomePageDataHandle * homePageDataHandle=[HomePageDataHandle sharedInstance];
//    获取segmentedControl
    UISegmentedControl * segmentedControl= (UISegmentedControl *) sender;
    switch (segmentedControl.selectedSegmentIndex) {
        case 0:
//            切换到最新视频视图
            [self goToTheLatestVideoTableView];
//            给最新视频数组分配空间,并赋初值
            self.theLatestVideoDataArray=[NSMutableArray array];
        {
//            定义theLatestVideoBlock
            __weak HomePageViewController * homePageVC=self;
            homePageDataHandle.theLatestVideoBlock= ^ void (NSMutableArray * array){
                homePageVC.theLatestVideoDataArray=array;
                [homePageVC.theLatestVideoTableView reloadData];
            };
        }
//            从网上请求数据
            [homePageDataHandle requestHomePageData:0 DataArray:self.theLatestVideoDataArray];
            break;
        case 1:
//            切换到比赛视频视图
            [self goToVideoGameTableView];
//            给比赛视频数组分配空间,并赋初值
            self.videoGameDataArray=[NSMutableArray array];
        {
//            定义videoGameBlock
            __weak HomePageViewController * homePageVC=self;
            homePageDataHandle.videoGameBlock= ^ void (NSMutableArray * array){
                homePageVC.videoGameDataArray=array;
                [homePageVC.videoGameTableView reloadData];
            };
        }
//            从网上请求数据
            [homePageDataHandle requestHomePageData:1 DataArray:self.videoGameDataArray];
            break ;
        case 2:
//            切换到高清视频视图
            [self goToHdBroadcastTableView];
//            给高清视频数组分配空间,并赋初值
            self.hdBroadcastDataArray=[NSMutableArray array];
        {
//            定义hdBroadcastBlock
            __weak HomePageViewController * homePageVC=self;
            homePageDataHandle.hdBroadcastBlock= ^ void (NSMutableArray * array){
                homePageVC.hdBroadcastDataArray=array;
                [homePageVC.hdBroadcastTableView reloadData];
            };
        }            
//            从网上请求求数据
            [homePageDataHandle requestHomePageData:2 DataArray:self.hdBroadcastDataArray];
            break ;
    }
    return ;
}

#pragma mark---切换到最新视频视图
- (void) goToTheLatestVideoTableView{
    if (self.videoGameTableView.superview!=nil) {
//        从比赛视频视图切换到最新视频视图
        [UIView transitionFromView:self.videoGameTableView toView:self.theLatestVideoTableView duration:1.0 options:UIViewAnimationOptionTransitionFlipFromLeft completion:nil];
    }else if(self.hdBroadcastTableView!=nil){
//        从高清视频视图切换到最新视频视图
        [UIView transitionFromView:self.hdBroadcastTableView toView:self.theLatestVideoTableView duration:1.0 options:UIViewAnimationOptionTransitionFlipFromLeft completion:nil];
    }else{
        return ;
    }
    return ;
}

#pragma mark---切换到比赛视频视图
- (void) goToVideoGameTableView{
    if(self.theLatestVideoTableView.superview!=nil){
//        从最新视频视图切换到比赛视频视图
        [UIView transitionFromView:self.theLatestVideoTableView toView:self.videoGameTableView duration:1.0 options:UIViewAnimationOptionTransitionFlipFromRight completion:nil];
    }else if(self.hdBroadcastTableView!=nil){
//        从高清视频视图切换到比赛视频视图
        [UIView transitionFromView:self.hdBroadcastTableView toView:self.videoGameTableView duration:1.0 options:UIViewAnimationOptionTransitionFlipFromLeft completion:nil];
    }else{
        return ;
    }
    return ;
}

#pragma mark---切换到高清直播视图
- (void) goToHdBroadcastTableView{
    if(self.theLatestVideoTableView.superview!=nil){
//        从最新视频视图切换到高清视频视图
        [UIView transitionFromView:self.theLatestVideoTableView toView:self.hdBroadcastTableView duration:1.0 options:UIViewAnimationOptionTransitionFlipFromRight completion:nil];
    }else if(self.videoGameTableView!=nil){
//        从比赛视频视图切换到高清视频视图
        [UIView transitionFromView:self.videoGameTableView toView:self.hdBroadcastTableView duration:1.0 options:UIViewAnimationOptionTransitionFlipFromRight completion:nil];
    }else{
        return ;
    }
    return ;
}

#pragma mark---创建theLatestVideoTableView并作为默认视图
- (void) createTheLatestVideoTableView{
//    创建theLatestVideoTableView
    self.theLatestVideoTableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([[UIScreen mainScreen] bounds]), CGRectGetHeight(self.containerView.frame)+70) style:UITableViewStylePlain];
//    将theLatestVideoTableView作为默认视图
    [self.containerView addSubview:self.theLatestVideoTableView];
//    设置代理
    self.theLatestVideoTableView.delegate=self;
    self.theLatestVideoTableView.dataSource=self;
//    设置theLatestVideoTableView的背景颜色
    self.theLatestVideoTableView.backgroundColor=[UIColor redColor];
//    设置theLatestVideoTableView的分割线样式
    self.theLatestVideoTableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
//    设置theLatestVideoTableView的分割线的颜色
    self.theLatestVideoTableView.separatorColor=[UIColor cyanColor];
//    注册需要的使用的cell
    [self.theLatestVideoTableView registerNib:[UINib nibWithNibName:@"CommonTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kTheLatestVideoTableViewCell];
    return ;
}

#pragma mark---创建videoGameTableView,暂不使用
- (void) createVideoGameTableView{
//    创建videoGameTableView
    self.videoGameTableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([[UIScreen mainScreen] bounds]), CGRectGetHeight(self.containerView.frame)+70) style:UITableViewStylePlain];
//    设置代理
    self.videoGameTableView.delegate=self;
    self.videoGameTableView.dataSource=self;
//    设置videoGameTableView的背景颜色
    self.videoGameTableView.backgroundColor=[UIColor blueColor];
//    设置videoGameTableView的分割线样式
    self.videoGameTableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
//    设置videoGameTableView的分割线的颜色
    self.videoGameTableView.separatorColor=[UIColor cyanColor];
//    注册需要的使用的cell
    [self.videoGameTableView registerNib:[UINib nibWithNibName:@"VideoGameTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kVideoGameTableViewCell];
    return ;
}

#pragma mark---创建hdBroadcastTableView,暂不使用
- (void) createHdBroadcastTableView{
//    创建hdBroadcastTableView
    self.hdBroadcastTableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([[UIScreen mainScreen] bounds]), CGRectGetHeight(self.containerView.frame)+70) style:UITableViewStylePlain];
//    设置代理
    self.hdBroadcastTableView.delegate=self;
    self.hdBroadcastTableView.dataSource=self;
//    设置hdBroadcastTableView的背景颜色
    self.hdBroadcastTableView.backgroundColor=[UIColor orangeColor];
//    设置hdBroadcastTableView的分割线样式
    self.hdBroadcastTableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
//    设置hdBroadcastTableView的分割线的颜色
    self.hdBroadcastTableView.separatorColor=[UIColor cyanColor];
//    注册需要的使用的cell
    [self.hdBroadcastTableView registerNib:[UINib nibWithNibName:@"CommonTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kHdBroadcastTableViewCell];
    return ;
}

#pragma mark---实现UITableViewDelegate,UITableViewDataSource协议中的方法
#pragma mark---设置某区的行数
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.homePageSegmentedControl.selectedSegmentIndex==0) {
        return [self.theLatestVideoDataArray count];
    }else if (self.homePageSegmentedControl.selectedSegmentIndex==1){
        return [self.videoGameDataArray count];
    }else if (self.homePageSegmentedControl.selectedSegmentIndex==2){
        return [self.hdBroadcastDataArray count];
    }else{
        return [self.searchDataArray count];
    }
}

#pragma mark---设置某行的内容
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.homePageSegmentedControl.selectedSegmentIndex==0) {
//    回收cell
        CommonTableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:kTheLatestVideoTableViewCell forIndexPath:indexPath];
//    回收不成功,就创建一个cell
        if (!cell) {
            cell=[[CommonTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kTheLatestVideoTableViewCell];
        }
//    找到对应的TheLatestVideoList对象
        TheLatestVideoList * theLatestVideoList=[self.theLatestVideoDataArray objectAtIndex:indexPath.row];
//    传值
        cell.theLatestVideoList=theLatestVideoList;
//    将信息显示在cell上
        [cell showTheLatestVideoListOnCommonTableViewCell];
        return cell;
    }else if (self.homePageSegmentedControl.selectedSegmentIndex==1){
//    回收cell
        VideoGameTableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:kVideoGameTableViewCell forIndexPath:indexPath];
//    回收不成功,就创建一个cell
        if (!cell) {
            cell=[[VideoGameTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kVideoGameTableViewCell];
        }
//    找到对应的VideoGameList对象
        VideoGameList * videoGameList=[self.videoGameDataArray objectAtIndex:indexPath.row];
//    传值
        cell.videoGameList=videoGameList;
//    将信息显示在cell上
        [cell showVideoGameListOnVideoGameTableViewCell];
        return cell;
    }else if (self.homePageSegmentedControl.selectedSegmentIndex==2){
//    回收cell
        CommonTableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:kHdBroadcastTableViewCell forIndexPath:indexPath];
//    回收不成功,就创建一个cell
        if (!cell) {
            cell=[[CommonTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kHdBroadcastTableViewCell];
        }
//    找到对应的HdBroadcastList对象
        HdBroadcastList * hdBroadcastList=[self.hdBroadcastDataArray objectAtIndex:indexPath.row];
//    传值
        cell.hdBroadcastList=hdBroadcastList;
//    将信息显示在cell上
        [cell showHdBroadcastListOnCommonTableViewCell];
        return cell;
    }else{
//        回收cell
        SearchTableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:kSearchTableViewCell forIndexPath:indexPath];
//        回收不成功,及创建一个cell
        if (!cell) {
            cell=[[SearchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kSearchTableViewCell];
        }
//        找到对应的对象searchTent
        SearchContent * searchContent=[self.searchDataArray objectAtIndex:indexPath.row];
//        将信息显示在cell上
        cell.textLabel.text=searchContent.title;
        return cell;
    }
    
}

#pragma mark---设置有多少分区
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

#pragma mark---设置某行的高度
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.searchBarTableView.tag==104) {
        return 30;
    }else{
        return 120;
    }
}

#pragma mark---点击cell触发的事件
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.homePageSegmentedControl.selectedSegmentIndex==0) {
//        找到对应的theLatestVideoList对象
        TheLatestVideoList * theLatestVideoList=[self.theLatestVideoDataArray objectAtIndex:indexPath.row];
        WebViewController * webVC=[[WebViewController alloc] initWithNibName:@"WebViewController" bundle:[NSBundle mainBundle]];
        UINavigationController * webNC=[[UINavigationController alloc] initWithRootViewController:webVC];
        webVC.navigationItem.title=theLatestVideoList.title;
        webVC.Url=theLatestVideoList.link;
        [self presentViewController:webNC animated:YES completion:nil];
        return ;
    }else if (self.homePageSegmentedControl.selectedSegmentIndex==1){
//        创建比赛视频详情视图控制器
        VideoGameDetailTableViewController * videoGameDetailTVC=[[VideoGameDetailTableViewController alloc] initWithNibName:@"VideoGameDetailTableViewController" bundle:[NSBundle mainBundle]];
//        将比赛视频详情视图控制器作为videoGameDetailNC的根视图控制器
        UINavigationController * videoGameDetailNC=[[UINavigationController alloc] initWithRootViewController:videoGameDetailTVC];
//    找到对应的VideoGameList对象
        VideoGameList * videoGameList=[self.videoGameDataArray objectAtIndex:indexPath.row];
//        传值
        videoGameDetailTVC.videoGameList=videoGameList;
//        设置比赛视频界面的标题
        videoGameDetailTVC.navigationItem.title=videoGameList.name;
//        模态推出比赛视频详情界面
        [self presentViewController:videoGameDetailNC animated:YES completion:nil];
        return ;
    }else if (self.homePageSegmentedControl.selectedSegmentIndex==2){
        return ;
    }else{
//        创建搜索视频详情视图控制器
        SearchVideoDetailTableViewController * searchVideoDetailTVC=[[SearchVideoDetailTableViewController alloc] initWithNibName:@"SearchVideoDetailTableViewController" bundle:[NSBundle mainBundle]];
//        将搜索视频详情视图控制器作为searchVideoDetailNC的根视图控制器
        UINavigationController * searchVideoDetailNC=[[UINavigationController alloc] initWithRootViewController:searchVideoDetailTVC];
//        找到对应的对象
        SearchContent * searchContent=[self.searchDataArray objectAtIndex:indexPath.row];
//        传值
        searchVideoDetailTVC.searchContent=searchContent;
//        设置搜索视频详情页面的标题
        searchVideoDetailTVC.navigationItem.title=searchContent.title;
//        模态推出搜索视频详情页面
        [self presentViewController:searchVideoDetailNC animated:YES completion:nil];
        return ;
    }
}

#pragma mark---显示更多的视频
- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.homePageSegmentedControl.selectedSegmentIndex==0) {
        if (indexPath.row==[self.theLatestVideoDataArray count]-1) {
//            获取单例对象
            HomePageDataHandle * homePageDataHandle=[HomePageDataHandle sharedInstance];
//            从网上请求数据
            [homePageDataHandle requestHomePageData:0 DataArray:self.theLatestVideoDataArray];
        }
    }
    return ;
}

#pragma mark---实现UISearchBarDelegate协议中的方法
#pragma mark---将要点击searchBar时触发的方法
- (BOOL) searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    self.homePageSearchBar.showsCancelButton=YES;
    self.searchBarTableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 64, CGRectGetWidth([[UIScreen mainScreen] bounds]), CGRectGetHeight([[UIScreen mainScreen] bounds])-64)];
    self.searchBarTableView.backgroundColor=[UIColor whiteColor];
    self.searchBarTableView.tag=104;
    if (self.homePageSegmentedControl.selectedSegmentIndex==0) {
        [self.theLatestVideoTableView removeFromSuperview];
    }else if (self.homePageSegmentedControl.selectedSegmentIndex==1){
        [self.videoGameTableView removeFromSuperview];
    }else if (self.homePageSegmentedControl.selectedSegmentIndex==2){
        [self.hdBroadcastTableView removeFromSuperview];
    }else{
        ;
    }
    self.segmentIndex=self.homePageSegmentedControl.selectedSegmentIndex;
    self.homePageSegmentedControl.selectedSegmentIndex=-1;
    [self.view addSubview:self.searchBarTableView];
//    设置代理
    self.searchBarTableView.delegate=self;
    self.searchBarTableView.dataSource=self;
//    注册所需要的cell
    [self.searchBarTableView registerNib:[UINib nibWithNibName:@"SearchTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kSearchTableViewCell];
//    添加取消
    self.buttonCancel=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.buttonCancel.frame = CGRectMake(CGRectGetMaxX(self.homePageSearchBar.frame)-65,CGRectGetMinY(self.homePageSearchBar.frame), 65, CGRectGetHeight(self.homePageSearchBar.frame)+2);
    [self.buttonCancel addTarget:self action:@selector(cancelToHomePage) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonCancel setBackgroundColor:[UIColor cyanColor]];
    self.buttonCancel.layer.cornerRadius=5;
    [self.buttonCancel setTitle:@"Cancel" forState:UIControlStateNormal];
    [self.view insertSubview:self.buttonCancel aboveSubview:self.homePageSearchBar];
    return  YES;
}

#pragma mark---实现给取消button添加的方法
- (void) cancelToHomePage{
    [self.homePageSearchBar isFirstResponder];
    self.homePageSearchBar.showsCancelButton=NO;
    [self.buttonCancel removeFromSuperview];
    [self.searchBarTableView removeFromSuperview];
    self.searchBarTableView.tag=0;
    self.homePageSegmentedControl.selectedSegmentIndex=self.segmentIndex;
    if (self.homePageSegmentedControl.selectedSegmentIndex==0) {
        [self.containerView addSubview:self.theLatestVideoTableView];
    }else if (self.homePageSegmentedControl.selectedSegmentIndex==1){
        [self.containerView addSubview:self.videoGameTableView];
    }else if (self.homePageSegmentedControl.selectedSegmentIndex==2){
        [self.containerView addSubview:self.hdBroadcastTableView];
    }else{
        ;
    }
    self.homePageSearchBar.text=@"";
    [self.homePageSearchBar resignFirstResponder];
    return ;
}

#pragma mark---编辑时开始搜索
- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
//    [self.searchDataArray removeAllObjects];
//    [self searchVideoBySearchText:searchText];
    return ;
}

#pragma mark---根据searchBar的内容搜索视频
- (void) searchVideoBySearchText:(NSString *) searchText{
//    异步连接下的GET请求
//    1.创建网址对象
    NSString * string=[[NSString stringWithFormat:kSearchVideoData_List_URL,searchText] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL * url=[NSURL URLWithString:string];
//    2.创建网络请求对象
    NSURLRequest * request=[NSURLRequest requestWithURL:url];
//    3.创建连接对象,并发送请求
    __weak HomePageViewController * homePageVC=self;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//        代码保护
        if (data==nil) {
            return ;
        }
//        4.解析数据
        NSDictionary * sourceDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//        处理数据(封装model对象)
        for (NSDictionary * dic in [sourceDic objectForKey:@"r"]) {
            SearchContent * searchContent=[[SearchContent alloc] init];
            [searchContent setValuesForKeysWithDictionary:dic];
            [homePageVC.searchDataArray addObject:searchContent];
        }
//        刷新数据
        [homePageVC.searchBarTableView reloadData];
    }];
    return ;
}

#pragma mark---懒加载搜索数组searchDataArray
- (NSMutableArray *) searchDataArray{
    if (_searchDataArray==nil) {
        self.searchDataArray=[NSMutableArray array];
    }
    return _searchDataArray;
}

#pragma mark---回收键盘
- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.searchDataArray removeAllObjects];
    [self searchVideoBySearchText:self.homePageSearchBar.text];
    self.homePageSearchBar.text=@"";
    [searchBar resignFirstResponder];
    return ;
}

@end
